package gitee

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"time"
	"xliu.com/giteebackup/pkg"
)

type GitRepoInfo struct {
	HtmlUrl        string    `json:"html_url"`
	SshUrl         string    `json:"ssh_url"`
	Name           string    `json:"human_name"`
	Description    string    `json:"description"`
	LastCommitTime time.Time `json:"pushed_at"`
}

type Repo struct {
	accessToken string
}

const (
	// TODO: 支持分页查询, 总数会在 Response Header 中，格式如 "total_count": "30" "total_page": "2"
	GetReposUrl = "https://gitee.com/api/v5/user/repos?access_token=%s&sort=full_name&page=1&per_page=100"
)

// check interface implementation
var _ pkg.GitApi = &Repo{}

func NewGiteeRepo(token string) Repo {
	return Repo{
		accessToken: token,
	}
}

func (g Repo) GetAllRepos() ([]pkg.RepoInfo, error) {
	client := http.Client{}

	resp, err := client.Get(fmt.Sprintf(GetReposUrl, g.accessToken))

	if err != nil {
		log.Println("get repos error", err)
		return nil, err
	}

	if resp.StatusCode != http.StatusOK {
		log.Println("get repos status", resp.StatusCode)
		return nil, errors.New("status code not 200")
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Println("read body error", err)
		return nil, err
	}

	var gitRepoInfos []GitRepoInfo

	err = json.Unmarshal(body, &gitRepoInfos)
	if err != nil {
		log.Println("json decode error", err)
		return nil, err
	}

	defer resp.Body.Close()

	var repos = make([]pkg.RepoInfo, len(gitRepoInfos))

	for idx, value := range gitRepoInfos {
		// 结构体的成员类型均一致，则可直接进行转换，go1.8后会忽略tag
		repos[idx] = pkg.RepoInfo(value)
	}

	return repos, err
}
